{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 第14章 自然语言处理：预训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import os\n",
    "import random\n",
    "import torch\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14.1 词嵌入（word2vec）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.1.1\n",
    "\n",
    "计算每个梯度的计算复杂度是多少？如果词表很大，会有什么问题呢？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;梯度的计算需要求函数在每个自变量方向上的偏导数，因此梯度的计算复杂度取决于自变量的数量。在书中，下列公式给出了计算单个中心词向量：\n",
    "\n",
    "$$\n",
    "{u_o}-{\\sum_{j \\in V}P({W_j}|{W_c}){u_j}}\n",
    "$$\n",
    "\n",
    "&emsp;&emsp;由上述公式可知，单计算一个中心词向量的梯度就需要计算以该词为中心词，所有词的条件概率。故其复杂度约为`len(V)^2`，如果词表太大，则计算量会相应呈平方增加，会使梯度求解的复杂度过大，不易更新权重;且词表过大，也会相应占据更大的存储空间，使训练更难进行。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.1.2\n",
    "\n",
    "英语中的一些固定短语由多个单词组成，例如“new york”。如何训练它们的词向量？提示:查看word2vec论文的第四节。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;在 word2vec 论文的第四节中，提到了两种训练固定短语词向量的方法：\n",
    "\n",
    "&emsp;&emsp;1.使用连字符（hyphen）将多个单词组合成一个词，例如 \"new-york\"。这样可以让算法将多个单词视为一个词来训练，从而学习到它们的词向量。但是这种方法对于较长的短语不太适用，因为可能会出现组合后的词太长的情况。\n",
    "\n",
    "&emsp;&emsp;2.使用特殊的标记将多个单词标记为一个短语，例如 \"< NewYork >\"。这种方法可以将多个单词组合成一个符号，从而在训练过程中将其作为一个整体来处理。这种方法可以适用于任何长度的短语。\n",
    "\n",
    "&emsp;&emsp;在实践中，使用哪种方法训练固定短语的词向量可以根据具体的应用场景和数据集来决定。如果数据集中包含大量的固定短语，那么使用第一种方法可能更加有效，因为它可以保留原始的单词信息并且不会损失信息；当短语长度差别很大时，使用第二种方法进行训练具有更强的通用性，可以更加有效地进行短语的表示。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.1.3\n",
    "\n",
    "让我们以跳元模型为例来思考word2vec设计。跳元模型中两个词向量的点积与余弦相似度之间有什么关系？对于语义相似的一对词，为什么它们的词向量（由跳元模型训练）的余弦相似度可能很高？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据相似度计算公式：\n",
    "$$\n",
    "cos(\\theta)=\\frac{\\mathbf{x^T} \\cdot \\mathbf{y}}{\\|\\mathbf{x}\\| \\|\\mathbf{y}\\|}\n",
    "$$\n",
    "&emsp;&emsp;上述公式表明余弦相似度就是两向量之间夹角的余弦值，所以两向量的内积越大，对应两向量的余弦相似度就越高。\n",
    "\n",
    "&emsp;&emsp;因为语义相近的一对词，在训练时上下文对应的词元也比较相似。这是因为跳元模型在训练时会尽可能地使中心词和上下文词的词向量在语义空间中更加接近。通俗来说，因为该对相似词表达的意思相近，故使用的语义也大致相同，所处语境也相似。故在跳连模型中进行训练时，往往会被训练成相似的向量。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14.2 近似训练"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.2.1\n",
    "\n",
    "如何在负采样中对噪声词进行采样？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;书中原文为“从预定义分布的$P(w)$中采样$K$个不是来自该上下文窗口的噪声词”，对于其中的预定义分布P(w),有如下的步骤：\n",
    "\n",
    "&emsp;&emsp;1.计算每个噪声词的采样概率 $P(w_i)$，一般使用词频的3/4次方来计算，公式如下：\n",
    "$$\n",
    "P(w_i) = \\frac{f(w_i)^{0.75}}{\\sum_{j=0}^n f(w_j)^{0.75}}\n",
    "$$\n",
    "&emsp;&emsp;其中，$f(w_i)$ 表示噪声词 $w_i$ 出现的频率。\n",
    "\n",
    "&emsp;&emsp;2.对每个负样本进行采样，可以使用轮盘赌算法（roulette wheel selection）或二元采样（binary search）等方法。\n",
    "\n",
    "&emsp;&emsp;**轮盘赌算法的具体步骤如下：**\n",
    "\n",
    "&emsp;&emsp;1.在 [0,1] 的范围内随机生成一个数 $r$。\n",
    "\n",
    "&emsp;&emsp;2.对于每个噪声词 $w_i$，将其采样概率 $P(w_i)$ 乘以一个系数 $k$，并将 $k$ 初始值设为 1。\n",
    "\n",
    "&emsp;&emsp;3.对所有的噪声词 $w_i$，按照采样概率 $P(w_i)k$ 的大小顺序排列。\n",
    "\n",
    "&emsp;&emsp;4.从排列后的噪声词中选择第一个概率累加和大于等于 $r$ 的噪声词作为采样结果。\n",
    "\n",
    "\n",
    "\n",
    "&emsp;&emsp;**二元采样的具体步骤如下：**\n",
    "\n",
    "&emsp;&emsp;1.在 [0,1] 的范围内随机生成一个数 $r$。\n",
    "\n",
    "&emsp;&emsp;2.对于每个噪声词 $w_i$，计算其累积分布函数（CDF）$F(w_i)$，即前 $i$ 个噪声词出现的总概率。\n",
    "\n",
    "&emsp;&emsp;3.对于每个噪声词 $w_i$，计算二元采样的阈值 $t_i$，即满足 $t_i > r$ 的最小 $t_i$ 值。\n",
    "\n",
    "&emsp;&emsp;4.在 $t_i$ 最小的噪声词 $w_i$ 对应的区间中进行采样。\n",
    "\n",
    "&emsp;&emsp;5.通过对噪声词进行采样，可以在训练中使用更少的负样本，从而提高训练速度和效果。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.2.2\n",
    "\n",
    "验证式（14.24）是否有效。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;由书中的层序softmax二叉树图可知，对于每一个除了根节点的节点，其左右都有一个对应的子节点即：\n",
    "$$\n",
    "P(w_i|w_c)=-P(w_{v-i}|w_c)\n",
    "$$\n",
    "其中$v$为词元数量。\n",
    "又由sigmoid公式可知：\n",
    "$$\n",
    "\\sigma=\\frac{1}{1+exp(-x)}\n",
    "$$\n",
    "若函数自变量互为相反数，则sigmoid函数相加为1。故可验证下式有效：\n",
    "$$\n",
    "\\sum_{w \\in V}P(w|w_c)=1\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.2.3\n",
    "\n",
    "如何分别使用负采样和分层softmax训练连续词袋模型？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;通过负采样训练连续词袋模型步骤如下：\n",
    "\n",
    "&emsp;&emsp;1.添加从预定义分布采样的负样本，以使得目标函数更有意义。\n",
    "\n",
    "&emsp;&emsp;2.根据给定上下文生成的的中心词，对上下文词向量进行平均计算条件概率。\n",
    "\n",
    "&emsp;&emsp;3.以连续词袋模型的似然函数进行梯度计算和参数权重的更新。\n",
    "\n",
    "&emsp;&emsp;采用层序训练softmax训练连续词袋模型步骤如下：\n",
    "\n",
    "&emsp;&emsp;1.建立词的二叉树向量表示。\n",
    "\n",
    "&emsp;&emsp;2.使用分层softmax近似条件概率。\n",
    "\n",
    "&emsp;&emsp;3.使用构造的词向量二叉树从根节点到叶结点构造损失函数。\n",
    "\n",
    "&emsp;&emsp;4.设定好权重和参数后进行权重更新。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14.3 用于预训练词嵌入的数据集"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.3.1\n",
    "\n",
    "如果不使用下采样，本节中代码的运行时间会发生什么变化？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;**先看一下原版代码运行时间:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@save\n",
    "def load_data_ptb(batch_size, max_window_size, num_noise_words):\n",
    "    \"\"\"下载PTB数据集，然后将其加载到内存中\"\"\"\n",
    "    num_workers = d2l.get_dataloader_workers()\n",
    "    sentences = d2l.read_ptb()\n",
    "    vocab = d2l.Vocab(sentences, min_freq=10)\n",
    "    subsampled, counter = d2l.subsample(sentences, vocab)\n",
    "    corpus = [vocab[line] for line in subsampled]\n",
    "    all_centers, all_contexts = d2l.get_centers_and_contexts(\n",
    "        corpus, max_window_size)\n",
    "    all_negatives = d2l.get_negatives(\n",
    "        all_contexts, vocab, counter, num_noise_words)\n",
    "    \n",
    "    class PTBDataset(torch.utils.data.Dataset):\n",
    "        def __init__(self, centers, contexts, negatives):\n",
    "            assert len(centers) == len(contexts) == len(negatives)\n",
    "            self.centers = centers\n",
    "            self.contexts = contexts\n",
    "            self.negatives = negatives\n",
    "            \n",
    "        def __getitem__(self, index):\n",
    "            return (self.centers[index], self.contexts[index],\n",
    "                self.negatives[index])\n",
    "        \n",
    "        def __len__(self):\n",
    "            return len(self.centers)\n",
    "        \n",
    "    dataset = PTBDataset(all_centers, all_contexts, all_negatives)\n",
    "    \n",
    "    data_iter = torch.utils.data.DataLoader(\n",
    "        dataset, batch_size, shuffle=True,\n",
    "        collate_fn=d2l.batchify, num_workers=num_workers)\n",
    "    return data_iter, vocab\n",
    "names = ['centers', 'contexts_negatives', 'masks', 'labels']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'd2l' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m----------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[4], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m timer \u001b[38;5;241m=\u001b[39m \u001b[43md2l\u001b[49m\u001b[38;5;241m.\u001b[39mTimer()\n\u001b[0;32m      2\u001b[0m timer\u001b[38;5;241m.\u001b[39mstart()\n\u001b[0;32m      3\u001b[0m data_iter, vocab \u001b[38;5;241m=\u001b[39m load_data_ptb2(\u001b[38;5;241m512\u001b[39m, \u001b[38;5;241m5\u001b[39m, \u001b[38;5;241m5\u001b[39m)\n",
      "\u001b[1;31mNameError\u001b[0m: name 'd2l' is not defined"
     ]
    }
   ],
   "source": [
    "timer = d2l.Timer()\n",
    "timer.start()\n",
    "data_iter, vocab = load_data_ptb2(512, 5, 5)\n",
    "timer.stop()\n",
    "print(timer.sum())\n",
    "for batch in data_iter:\n",
    "    for name, data in zip(names, batch):\n",
    "        print(name, 'shape:', data.shape)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;**再看一下不使用下采样的:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@save\n",
    "def load_data_ptb2(batch_size, max_window_size, num_noise_words):\n",
    "    \"\"\"下载PTB数据集，然后将其加载到内存中\"\"\"\n",
    "    num_workers = d2l.get_dataloader_workers()\n",
    "    sentences = d2l.read_ptb()\n",
    "    vocab = d2l.Vocab(sentences, min_freq=10)\n",
    "    subsampled, counter = d2l.subsample(sentences, vocab)\n",
    "    corpus = [vocab[line] for line in sentences]\n",
    "    all_centers, all_contexts = d2l.get_centers_and_contexts(\n",
    "        corpus, max_window_size)\n",
    "    all_negatives = d2l.get_negatives(\n",
    "        all_contexts, vocab, counter, num_noise_words)\n",
    "    \n",
    "    class PTBDataset(torch.utils.data.Dataset):\n",
    "        def __init__(self, centers, contexts, negatives):\n",
    "            assert len(centers) == len(contexts) == len(negatives)\n",
    "            self.centers = centers\n",
    "            self.contexts = contexts\n",
    "            self.negatives = negatives\n",
    "            \n",
    "        def __getitem__(self, index):\n",
    "            return (self.centers[index], self.contexts[index],\n",
    "                self.negatives[index])\n",
    "        \n",
    "        def __len__(self):\n",
    "            return len(self.centers)\n",
    "        \n",
    "    dataset = PTBDataset(all_centers, all_contexts, all_negatives)\n",
    "    \n",
    "    data_iter = torch.utils.data.DataLoader(\n",
    "        dataset, batch_size, shuffle=True,\n",
    "        collate_fn=d2l.batchify, num_workers=num_workers)\n",
    "    return data_iter, vocab\n",
    "names = ['centers', 'contexts_negatives', 'masks', 'labels']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22.780914545059204\n",
      "centers shape: torch.Size([512, 1])\n",
      "contexts_negatives shape: torch.Size([512, 60])\n",
      "masks shape: torch.Size([512, 60])\n",
      "labels shape: torch.Size([512, 60])\n"
     ]
    }
   ],
   "source": [
    "timer = d2l.Timer()\n",
    "timer.start()\n",
    "data_iter, vocab = load_data_ptb2(512, 5, 5)\n",
    "timer.stop()\n",
    "print(timer.sum())\n",
    "for batch in data_iter:\n",
    "    for name, data in zip(names, batch):\n",
    "        print(name, 'shape:', data.shape)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;可见，不使用下采样，大量的高频词会使运行时间显著增加"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.3.2\n",
    "\n",
    "`RandomGenerator`类缓存`k`个随机采样结果。将`k`设置为其他值，看看它如何影响数据加载速度。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;前面定义可知，采取负采样时，K表示对每一对中心-上下文词随机抽取的噪声词，K越大表示从vocab里面抽取的次数越多，所以相应数据加载速度越大。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "13.228698968887329\n",
      "centers shape: torch.Size([512, 1])\n",
      "contexts_negatives shape: torch.Size([512, 110])\n",
      "masks shape: torch.Size([512, 110])\n",
      "labels shape: torch.Size([512, 110])\n"
     ]
    }
   ],
   "source": [
    "timer = d2l.Timer()\n",
    "timer.start()\n",
    "data_iter, vocab = load_data_ptb(512, 5, 10)\n",
    "timer.stop()\n",
    "print(timer.sum())\n",
    "for batch in data_iter:\n",
    "    for name, data in zip(names, batch):\n",
    "        print(name, 'shape:', data.shape)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;**对以上三次运行时间总结:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       "  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"326.803125pt\" height=\"281.9125pt\" viewBox=\"0 0 326.803125 281.9125\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2023-05-07T09:44:11.144538</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.5.1, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 281.9125 \n",
       "L 326.803125 281.9125 \n",
       "L 326.803125 0 \n",
       "L 0 0 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 40.603125 244.078125 \n",
       "L 319.603125 244.078125 \n",
       "L 319.603125 22.318125 \n",
       "L 40.603125 22.318125 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 53.284943 244.078125 \n",
       "L 125.752476 244.078125 \n",
       "L 125.752476 174.079881 \n",
       "L 53.284943 174.079881 \n",
       "z\n",
       "\" clip-path=\"url(#p660f5ca98f)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 143.869359 244.078125 \n",
       "L 216.336891 244.078125 \n",
       "L 216.336891 32.878125 \n",
       "L 143.869359 32.878125 \n",
       "z\n",
       "\" clip-path=\"url(#p660f5ca98f)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 234.453774 244.078125 \n",
       "L 306.921307 244.078125 \n",
       "L 306.921307 121.41895 \n",
       "L 234.453774 121.41895 \n",
       "z\n",
       "\" clip-path=\"url(#p660f5ca98f)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <defs>\n",
       "       <path id=\"m3633bc86a4\" d=\"M 0 0 \n",
       "L 0 3.5 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3633bc86a4\" x=\"89.518709\" y=\"244.078125\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_1\">\n",
       "      <!-- ori -->\n",
       "      <g transform=\"translate(83.014803 258.676563)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \n",
       "Q 1497 3097 1228 2736 \n",
       "Q 959 2375 959 1747 \n",
       "Q 959 1119 1226 758 \n",
       "Q 1494 397 1959 397 \n",
       "Q 2419 397 2687 759 \n",
       "Q 2956 1122 2956 1747 \n",
       "Q 2956 2369 2687 2733 \n",
       "Q 2419 3097 1959 3097 \n",
       "z\n",
       "M 1959 3584 \n",
       "Q 2709 3584 3137 3096 \n",
       "Q 3566 2609 3566 1747 \n",
       "Q 3566 888 3137 398 \n",
       "Q 2709 -91 1959 -91 \n",
       "Q 1206 -91 779 398 \n",
       "Q 353 888 353 1747 \n",
       "Q 353 2609 779 3096 \n",
       "Q 1206 3584 1959 3584 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \n",
       "Q 2534 3019 2420 3045 \n",
       "Q 2306 3072 2169 3072 \n",
       "Q 1681 3072 1420 2755 \n",
       "Q 1159 2438 1159 1844 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1341 3275 1631 3429 \n",
       "Q 1922 3584 2338 3584 \n",
       "Q 2397 3584 2469 3576 \n",
       "Q 2541 3569 2628 3553 \n",
       "L 2631 2963 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-69\" d=\"M 603 3500 \n",
       "L 1178 3500 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 3500 \n",
       "z\n",
       "M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 4134 \n",
       "L 603 4134 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-6f\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-72\" x=\"61.181641\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-69\" x=\"102.294922\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_2\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3633bc86a4\" x=\"180.103125\" y=\"244.078125\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_2\">\n",
       "      <!-- no_subsampling -->\n",
       "      <g transform=\"translate(139.592969 258.676563)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-5f\" d=\"M 3263 -1063 \n",
       "L 3263 -1509 \n",
       "L -63 -1509 \n",
       "L -63 -1063 \n",
       "L 3263 -1063 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \n",
       "L 2834 2853 \n",
       "Q 2591 2978 2328 3040 \n",
       "Q 2066 3103 1784 3103 \n",
       "Q 1356 3103 1142 2972 \n",
       "Q 928 2841 928 2578 \n",
       "Q 928 2378 1081 2264 \n",
       "Q 1234 2150 1697 2047 \n",
       "L 1894 2003 \n",
       "Q 2506 1872 2764 1633 \n",
       "Q 3022 1394 3022 966 \n",
       "Q 3022 478 2636 193 \n",
       "Q 2250 -91 1575 -91 \n",
       "Q 1294 -91 989 -36 \n",
       "Q 684 19 347 128 \n",
       "L 347 722 \n",
       "Q 666 556 975 473 \n",
       "Q 1284 391 1588 391 \n",
       "Q 1994 391 2212 530 \n",
       "Q 2431 669 2431 922 \n",
       "Q 2431 1156 2273 1281 \n",
       "Q 2116 1406 1581 1522 \n",
       "L 1381 1569 \n",
       "Q 847 1681 609 1914 \n",
       "Q 372 2147 372 2553 \n",
       "Q 372 3047 722 3315 \n",
       "Q 1072 3584 1716 3584 \n",
       "Q 2034 3584 2315 3537 \n",
       "Q 2597 3491 2834 3397 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-75\" d=\"M 544 1381 \n",
       "L 544 3500 \n",
       "L 1119 3500 \n",
       "L 1119 1403 \n",
       "Q 1119 906 1312 657 \n",
       "Q 1506 409 1894 409 \n",
       "Q 2359 409 2629 706 \n",
       "Q 2900 1003 2900 1516 \n",
       "L 2900 3500 \n",
       "L 3475 3500 \n",
       "L 3475 0 \n",
       "L 2900 0 \n",
       "L 2900 538 \n",
       "Q 2691 219 2414 64 \n",
       "Q 2138 -91 1772 -91 \n",
       "Q 1169 -91 856 284 \n",
       "Q 544 659 544 1381 \n",
       "z\n",
       "M 1991 3584 \n",
       "L 1991 3584 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-62\" d=\"M 3116 1747 \n",
       "Q 3116 2381 2855 2742 \n",
       "Q 2594 3103 2138 3103 \n",
       "Q 1681 3103 1420 2742 \n",
       "Q 1159 2381 1159 1747 \n",
       "Q 1159 1113 1420 752 \n",
       "Q 1681 391 2138 391 \n",
       "Q 2594 391 2855 752 \n",
       "Q 3116 1113 3116 1747 \n",
       "z\n",
       "M 1159 2969 \n",
       "Q 1341 3281 1617 3432 \n",
       "Q 1894 3584 2278 3584 \n",
       "Q 2916 3584 3314 3078 \n",
       "Q 3713 2572 3713 1747 \n",
       "Q 3713 922 3314 415 \n",
       "Q 2916 -91 2278 -91 \n",
       "Q 1894 -91 1617 61 \n",
       "Q 1341 213 1159 525 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 2969 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \n",
       "Q 1497 1759 1228 1600 \n",
       "Q 959 1441 959 1056 \n",
       "Q 959 750 1161 570 \n",
       "Q 1363 391 1709 391 \n",
       "Q 2188 391 2477 730 \n",
       "Q 2766 1069 2766 1631 \n",
       "L 2766 1759 \n",
       "L 2194 1759 \n",
       "z\n",
       "M 3341 1997 \n",
       "L 3341 0 \n",
       "L 2766 0 \n",
       "L 2766 531 \n",
       "Q 2569 213 2275 61 \n",
       "Q 1981 -91 1556 -91 \n",
       "Q 1019 -91 701 211 \n",
       "Q 384 513 384 1019 \n",
       "Q 384 1609 779 1909 \n",
       "Q 1175 2209 1959 2209 \n",
       "L 2766 2209 \n",
       "L 2766 2266 \n",
       "Q 2766 2663 2505 2880 \n",
       "Q 2244 3097 1772 3097 \n",
       "Q 1472 3097 1187 3025 \n",
       "Q 903 2953 641 2809 \n",
       "L 641 3341 \n",
       "Q 956 3463 1253 3523 \n",
       "Q 1550 3584 1831 3584 \n",
       "Q 2591 3584 2966 3190 \n",
       "Q 3341 2797 3341 1997 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-6d\" d=\"M 3328 2828 \n",
       "Q 3544 3216 3844 3400 \n",
       "Q 4144 3584 4550 3584 \n",
       "Q 5097 3584 5394 3201 \n",
       "Q 5691 2819 5691 2113 \n",
       "L 5691 0 \n",
       "L 5113 0 \n",
       "L 5113 2094 \n",
       "Q 5113 2597 4934 2840 \n",
       "Q 4756 3084 4391 3084 \n",
       "Q 3944 3084 3684 2787 \n",
       "Q 3425 2491 3425 1978 \n",
       "L 3425 0 \n",
       "L 2847 0 \n",
       "L 2847 2094 \n",
       "Q 2847 2600 2669 2842 \n",
       "Q 2491 3084 2119 3084 \n",
       "Q 1678 3084 1418 2786 \n",
       "Q 1159 2488 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1356 3278 1631 3431 \n",
       "Q 1906 3584 2284 3584 \n",
       "Q 2666 3584 2933 3390 \n",
       "Q 3200 3197 3328 2828 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-70\" d=\"M 1159 525 \n",
       "L 1159 -1331 \n",
       "L 581 -1331 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2969 \n",
       "Q 1341 3281 1617 3432 \n",
       "Q 1894 3584 2278 3584 \n",
       "Q 2916 3584 3314 3078 \n",
       "Q 3713 2572 3713 1747 \n",
       "Q 3713 922 3314 415 \n",
       "Q 2916 -91 2278 -91 \n",
       "Q 1894 -91 1617 61 \n",
       "Q 1341 213 1159 525 \n",
       "z\n",
       "M 3116 1747 \n",
       "Q 3116 2381 2855 2742 \n",
       "Q 2594 3103 2138 3103 \n",
       "Q 1681 3103 1420 2742 \n",
       "Q 1159 2381 1159 1747 \n",
       "Q 1159 1113 1420 752 \n",
       "Q 1681 391 2138 391 \n",
       "Q 2594 391 2855 752 \n",
       "Q 3116 1113 3116 1747 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-67\" d=\"M 2906 1791 \n",
       "Q 2906 2416 2648 2759 \n",
       "Q 2391 3103 1925 3103 \n",
       "Q 1463 3103 1205 2759 \n",
       "Q 947 2416 947 1791 \n",
       "Q 947 1169 1205 825 \n",
       "Q 1463 481 1925 481 \n",
       "Q 2391 481 2648 825 \n",
       "Q 2906 1169 2906 1791 \n",
       "z\n",
       "M 3481 434 \n",
       "Q 3481 -459 3084 -895 \n",
       "Q 2688 -1331 1869 -1331 \n",
       "Q 1566 -1331 1297 -1286 \n",
       "Q 1028 -1241 775 -1147 \n",
       "L 775 -588 \n",
       "Q 1028 -725 1275 -790 \n",
       "Q 1522 -856 1778 -856 \n",
       "Q 2344 -856 2625 -561 \n",
       "Q 2906 -266 2906 331 \n",
       "L 2906 616 \n",
       "Q 2728 306 2450 153 \n",
       "Q 2172 0 1784 0 \n",
       "Q 1141 0 747 490 \n",
       "Q 353 981 353 1791 \n",
       "Q 353 2603 747 3093 \n",
       "Q 1141 3584 1784 3584 \n",
       "Q 2172 3584 2450 3431 \n",
       "Q 2728 3278 2906 2969 \n",
       "L 2906 3500 \n",
       "L 3481 3500 \n",
       "L 3481 434 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-6e\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6f\" x=\"63.378906\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-5f\" x=\"124.560547\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-73\" x=\"174.560547\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-75\" x=\"226.660156\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-62\" x=\"290.039062\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-73\" x=\"353.515625\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-61\" x=\"405.615234\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6d\" x=\"466.894531\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-70\" x=\"564.306641\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6c\" x=\"627.783203\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-69\" x=\"655.566406\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6e\" x=\"683.349609\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-67\" x=\"746.728516\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3633bc86a4\" x=\"270.687541\" y=\"244.078125\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_3\">\n",
       "      <!-- enhance_k -->\n",
       "      <g transform=\"translate(243.819572 258.676563)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \n",
       "L 3597 1613 \n",
       "L 953 1613 \n",
       "Q 991 1019 1311 708 \n",
       "Q 1631 397 2203 397 \n",
       "Q 2534 397 2845 478 \n",
       "Q 3156 559 3463 722 \n",
       "L 3463 178 \n",
       "Q 3153 47 2828 -22 \n",
       "Q 2503 -91 2169 -91 \n",
       "Q 1331 -91 842 396 \n",
       "Q 353 884 353 1716 \n",
       "Q 353 2575 817 3079 \n",
       "Q 1281 3584 2069 3584 \n",
       "Q 2775 3584 3186 3129 \n",
       "Q 3597 2675 3597 1894 \n",
       "z\n",
       "M 3022 2063 \n",
       "Q 3016 2534 2758 2815 \n",
       "Q 2500 3097 2075 3097 \n",
       "Q 1594 3097 1305 2825 \n",
       "Q 1016 2553 972 2059 \n",
       "L 3022 2063 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \n",
       "L 3122 2828 \n",
       "Q 2878 2963 2633 3030 \n",
       "Q 2388 3097 2138 3097 \n",
       "Q 1578 3097 1268 2742 \n",
       "Q 959 2388 959 1747 \n",
       "Q 959 1106 1268 751 \n",
       "Q 1578 397 2138 397 \n",
       "Q 2388 397 2633 464 \n",
       "Q 2878 531 3122 666 \n",
       "L 3122 134 \n",
       "Q 2881 22 2623 -34 \n",
       "Q 2366 -91 2075 -91 \n",
       "Q 1284 -91 818 406 \n",
       "Q 353 903 353 1747 \n",
       "Q 353 2603 823 3093 \n",
       "Q 1294 3584 2113 3584 \n",
       "Q 2378 3584 2631 3529 \n",
       "Q 2884 3475 3122 3366 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-6b\" d=\"M 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 1991 \n",
       "L 2875 3500 \n",
       "L 3609 3500 \n",
       "L 1753 1863 \n",
       "L 3688 0 \n",
       "L 2938 0 \n",
       "L 1159 1709 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-65\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6e\" x=\"61.523438\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-68\" x=\"124.902344\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-61\" x=\"188.28125\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6e\" x=\"249.560547\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-63\" x=\"312.939453\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-65\" x=\"367.919922\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-5f\" x=\"429.443359\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6b\" x=\"479.443359\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_4\">\n",
       "     <!-- Program -->\n",
       "     <g transform=\"translate(159.009375 272.632812)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-50\" d=\"M 1259 4147 \n",
       "L 1259 2394 \n",
       "L 2053 2394 \n",
       "Q 2494 2394 2734 2622 \n",
       "Q 2975 2850 2975 3272 \n",
       "Q 2975 3691 2734 3919 \n",
       "Q 2494 4147 2053 4147 \n",
       "L 1259 4147 \n",
       "z\n",
       "M 628 4666 \n",
       "L 2053 4666 \n",
       "Q 2838 4666 3239 4311 \n",
       "Q 3641 3956 3641 3272 \n",
       "Q 3641 2581 3239 2228 \n",
       "Q 2838 1875 2053 1875 \n",
       "L 1259 1875 \n",
       "L 1259 0 \n",
       "L 628 0 \n",
       "L 628 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-50\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-72\" x=\"58.552734\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" x=\"97.416016\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-67\" x=\"158.597656\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-72\" x=\"222.074219\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-61\" x=\"263.1875\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6d\" x=\"324.466797\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_4\">\n",
       "      <defs>\n",
       "       <path id=\"m4151cd3adf\" d=\"M 0 0 \n",
       "L -3.5 0 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m4151cd3adf\" x=\"40.603125\" y=\"244.078125\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_5\">\n",
       "      <!-- 0 -->\n",
       "      <g transform=\"translate(27.240625 247.877344)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \n",
       "Q 1547 4250 1301 3770 \n",
       "Q 1056 3291 1056 2328 \n",
       "Q 1056 1369 1301 889 \n",
       "Q 1547 409 2034 409 \n",
       "Q 2525 409 2770 889 \n",
       "Q 3016 1369 3016 2328 \n",
       "Q 3016 3291 2770 3770 \n",
       "Q 2525 4250 2034 4250 \n",
       "z\n",
       "M 2034 4750 \n",
       "Q 2819 4750 3233 4129 \n",
       "Q 3647 3509 3647 2328 \n",
       "Q 3647 1150 3233 529 \n",
       "Q 2819 -91 2034 -91 \n",
       "Q 1250 -91 836 529 \n",
       "Q 422 1150 422 2328 \n",
       "Q 422 3509 836 4129 \n",
       "Q 1250 4750 2034 4750 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m4151cd3adf\" x=\"40.603125\" y=\"197.721672\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_6\">\n",
       "      <!-- 5 -->\n",
       "      <g transform=\"translate(27.240625 201.520891)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \n",
       "L 3169 4666 \n",
       "L 3169 4134 \n",
       "L 1269 4134 \n",
       "L 1269 2991 \n",
       "Q 1406 3038 1543 3061 \n",
       "Q 1681 3084 1819 3084 \n",
       "Q 2600 3084 3056 2656 \n",
       "Q 3513 2228 3513 1497 \n",
       "Q 3513 744 3044 326 \n",
       "Q 2575 -91 1722 -91 \n",
       "Q 1428 -91 1123 -41 \n",
       "Q 819 9 494 109 \n",
       "L 494 744 \n",
       "Q 775 591 1075 516 \n",
       "Q 1375 441 1709 441 \n",
       "Q 2250 441 2565 725 \n",
       "Q 2881 1009 2881 1497 \n",
       "Q 2881 1984 2565 2268 \n",
       "Q 2250 2553 1709 2553 \n",
       "Q 1456 2553 1204 2497 \n",
       "Q 953 2441 691 2322 \n",
       "L 691 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m4151cd3adf\" x=\"40.603125\" y=\"151.365219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_7\">\n",
       "      <!-- 10 -->\n",
       "      <g transform=\"translate(20.878125 155.164438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-31\" d=\"M 794 531 \n",
       "L 1825 531 \n",
       "L 1825 4091 \n",
       "L 703 3866 \n",
       "L 703 4441 \n",
       "L 1819 4666 \n",
       "L 2450 4666 \n",
       "L 2450 531 \n",
       "L 3481 531 \n",
       "L 3481 0 \n",
       "L 794 0 \n",
       "L 794 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m4151cd3adf\" x=\"40.603125\" y=\"105.008766\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_8\">\n",
       "      <!-- 15 -->\n",
       "      <g transform=\"translate(20.878125 108.807985)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"63.623047\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_5\">\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m4151cd3adf\" x=\"40.603125\" y=\"58.652313\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_9\">\n",
       "      <!-- 20 -->\n",
       "      <g transform=\"translate(20.878125 62.451532)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \n",
       "L 3431 531 \n",
       "L 3431 0 \n",
       "L 469 0 \n",
       "L 469 531 \n",
       "Q 828 903 1448 1529 \n",
       "Q 2069 2156 2228 2338 \n",
       "Q 2531 2678 2651 2914 \n",
       "Q 2772 3150 2772 3378 \n",
       "Q 2772 3750 2511 3984 \n",
       "Q 2250 4219 1831 4219 \n",
       "Q 1534 4219 1204 4116 \n",
       "Q 875 4013 500 3803 \n",
       "L 500 4441 \n",
       "Q 881 4594 1212 4672 \n",
       "Q 1544 4750 1819 4750 \n",
       "Q 2544 4750 2975 4387 \n",
       "Q 3406 4025 3406 3419 \n",
       "Q 3406 3131 3298 2873 \n",
       "Q 3191 2616 2906 2266 \n",
       "Q 2828 2175 2409 1742 \n",
       "Q 1991 1309 1228 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_10\">\n",
       "     <!-- Running Time (s) -->\n",
       "     <g transform=\"translate(14.798438 175.603594)rotate(-90)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-52\" d=\"M 2841 2188 \n",
       "Q 3044 2119 3236 1894 \n",
       "Q 3428 1669 3622 1275 \n",
       "L 4263 0 \n",
       "L 3584 0 \n",
       "L 2988 1197 \n",
       "Q 2756 1666 2539 1819 \n",
       "Q 2322 1972 1947 1972 \n",
       "L 1259 1972 \n",
       "L 1259 0 \n",
       "L 628 0 \n",
       "L 628 4666 \n",
       "L 2053 4666 \n",
       "Q 2853 4666 3247 4331 \n",
       "Q 3641 3997 3641 3322 \n",
       "Q 3641 2881 3436 2590 \n",
       "Q 3231 2300 2841 2188 \n",
       "z\n",
       "M 1259 4147 \n",
       "L 1259 2491 \n",
       "L 2053 2491 \n",
       "Q 2509 2491 2742 2702 \n",
       "Q 2975 2913 2975 3322 \n",
       "Q 2975 3731 2742 3939 \n",
       "Q 2509 4147 2053 4147 \n",
       "L 1259 4147 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-20\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-54\" d=\"M -19 4666 \n",
       "L 3928 4666 \n",
       "L 3928 4134 \n",
       "L 2272 4134 \n",
       "L 2272 0 \n",
       "L 1638 0 \n",
       "L 1638 4134 \n",
       "L -19 4134 \n",
       "L -19 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-28\" d=\"M 1984 4856 \n",
       "Q 1566 4138 1362 3434 \n",
       "Q 1159 2731 1159 2009 \n",
       "Q 1159 1288 1364 580 \n",
       "Q 1569 -128 1984 -844 \n",
       "L 1484 -844 \n",
       "Q 1016 -109 783 600 \n",
       "Q 550 1309 550 2009 \n",
       "Q 550 2706 781 3412 \n",
       "Q 1013 4119 1484 4856 \n",
       "L 1984 4856 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-29\" d=\"M 513 4856 \n",
       "L 1013 4856 \n",
       "Q 1481 4119 1714 3412 \n",
       "Q 1947 2706 1947 2009 \n",
       "Q 1947 1309 1714 600 \n",
       "Q 1481 -109 1013 -844 \n",
       "L 513 -844 \n",
       "Q 928 -128 1133 580 \n",
       "Q 1338 1288 1338 2009 \n",
       "Q 1338 2731 1133 3434 \n",
       "Q 928 4138 513 4856 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-52\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-75\" x=\"64.982422\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"128.361328\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"191.740234\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" x=\"255.119141\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"282.902344\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-67\" x=\"346.28125\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-20\" x=\"409.757812\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-54\" x=\"441.544922\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" x=\"499.503906\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6d\" x=\"527.287109\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"624.699219\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-20\" x=\"686.222656\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-28\" x=\"718.009766\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" x=\"757.023438\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-29\" x=\"809.123047\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 40.603125 244.078125 \n",
       "L 40.603125 22.318125 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_7\">\n",
       "    <path d=\"M 319.603125 244.078125 \n",
       "L 319.603125 22.318125 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_8\">\n",
       "    <path d=\"M 40.603125 244.078125 \n",
       "L 319.603125 244.078125 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_9\">\n",
       "    <path d=\"M 40.603125 22.318125 \n",
       "L 319.603125 22.318125 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"text_11\">\n",
       "    <!-- 7.55 -->\n",
       "    <g transform=\"translate(78.385897 172.000193)scale(0.1 -0.1)\">\n",
       "     <defs>\n",
       "      <path id=\"DejaVuSans-37\" d=\"M 525 4666 \n",
       "L 3525 4666 \n",
       "L 3525 4397 \n",
       "L 1831 0 \n",
       "L 1172 0 \n",
       "L 2766 4134 \n",
       "L 525 4134 \n",
       "L 525 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-2e\" d=\"M 684 794 \n",
       "L 1344 794 \n",
       "L 1344 0 \n",
       "L 684 0 \n",
       "L 684 794 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "     </defs>\n",
       "     <use xlink:href=\"#DejaVuSans-37\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-35\" x=\"95.410156\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-35\" x=\"159.033203\"/>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"text_12\">\n",
       "    <!-- 22.78 -->\n",
       "    <g transform=\"translate(165.789062 30.798437)scale(0.1 -0.1)\">\n",
       "     <defs>\n",
       "      <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \n",
       "Q 1584 2216 1326 1975 \n",
       "Q 1069 1734 1069 1313 \n",
       "Q 1069 891 1326 650 \n",
       "Q 1584 409 2034 409 \n",
       "Q 2484 409 2743 651 \n",
       "Q 3003 894 3003 1313 \n",
       "Q 3003 1734 2745 1975 \n",
       "Q 2488 2216 2034 2216 \n",
       "z\n",
       "M 1403 2484 \n",
       "Q 997 2584 770 2862 \n",
       "Q 544 3141 544 3541 \n",
       "Q 544 4100 942 4425 \n",
       "Q 1341 4750 2034 4750 \n",
       "Q 2731 4750 3128 4425 \n",
       "Q 3525 4100 3525 3541 \n",
       "Q 3525 3141 3298 2862 \n",
       "Q 3072 2584 2669 2484 \n",
       "Q 3125 2378 3379 2068 \n",
       "Q 3634 1759 3634 1313 \n",
       "Q 3634 634 3220 271 \n",
       "Q 2806 -91 2034 -91 \n",
       "Q 1263 -91 848 271 \n",
       "Q 434 634 434 1313 \n",
       "Q 434 1759 690 2068 \n",
       "Q 947 2378 1403 2484 \n",
       "z\n",
       "M 1172 3481 \n",
       "Q 1172 3119 1398 2916 \n",
       "Q 1625 2713 2034 2713 \n",
       "Q 2441 2713 2670 2916 \n",
       "Q 2900 3119 2900 3481 \n",
       "Q 2900 3844 2670 4047 \n",
       "Q 2441 4250 2034 4250 \n",
       "Q 1625 4250 1398 4047 \n",
       "Q 1172 3844 1172 3481 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "     </defs>\n",
       "     <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-32\" x=\"63.623047\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-2e\" x=\"127.246094\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-37\" x=\"159.033203\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-38\" x=\"222.65625\"/>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"text_13\">\n",
       "    <!-- 13.23 -->\n",
       "    <g transform=\"translate(256.373478 119.339263)scale(0.1 -0.1)\">\n",
       "     <defs>\n",
       "      <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \n",
       "Q 3050 2419 3304 2112 \n",
       "Q 3559 1806 3559 1356 \n",
       "Q 3559 666 3084 287 \n",
       "Q 2609 -91 1734 -91 \n",
       "Q 1441 -91 1130 -33 \n",
       "Q 819 25 488 141 \n",
       "L 488 750 \n",
       "Q 750 597 1062 519 \n",
       "Q 1375 441 1716 441 \n",
       "Q 2309 441 2620 675 \n",
       "Q 2931 909 2931 1356 \n",
       "Q 2931 1769 2642 2001 \n",
       "Q 2353 2234 1838 2234 \n",
       "L 1294 2234 \n",
       "L 1294 2753 \n",
       "L 1863 2753 \n",
       "Q 2328 2753 2575 2939 \n",
       "Q 2822 3125 2822 3475 \n",
       "Q 2822 3834 2567 4026 \n",
       "Q 2313 4219 1838 4219 \n",
       "Q 1578 4219 1281 4162 \n",
       "Q 984 4106 628 3988 \n",
       "L 628 4550 \n",
       "Q 988 4650 1302 4700 \n",
       "Q 1616 4750 1894 4750 \n",
       "Q 2613 4750 3031 4423 \n",
       "Q 3450 4097 3450 3541 \n",
       "Q 3450 3153 3228 2886 \n",
       "Q 3006 2619 2597 2516 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "     </defs>\n",
       "     <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-33\" x=\"63.623047\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-2e\" x=\"127.246094\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-32\" x=\"159.033203\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-33\" x=\"222.65625\"/>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"text_14\">\n",
       "    <!-- Program Running Time Comparison -->\n",
       "    <g transform=\"translate(73.880625 16.318125)scale(0.12 -0.12)\">\n",
       "     <defs>\n",
       "      <path id=\"DejaVuSans-43\" d=\"M 4122 4306 \n",
       "L 4122 3641 \n",
       "Q 3803 3938 3442 4084 \n",
       "Q 3081 4231 2675 4231 \n",
       "Q 1875 4231 1450 3742 \n",
       "Q 1025 3253 1025 2328 \n",
       "Q 1025 1406 1450 917 \n",
       "Q 1875 428 2675 428 \n",
       "Q 3081 428 3442 575 \n",
       "Q 3803 722 4122 1019 \n",
       "L 4122 359 \n",
       "Q 3791 134 3420 21 \n",
       "Q 3050 -91 2638 -91 \n",
       "Q 1578 -91 968 557 \n",
       "Q 359 1206 359 2328 \n",
       "Q 359 3453 968 4101 \n",
       "Q 1578 4750 2638 4750 \n",
       "Q 3056 4750 3426 4639 \n",
       "Q 3797 4528 4122 4306 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "     </defs>\n",
       "     <use xlink:href=\"#DejaVuSans-50\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-72\" x=\"58.552734\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6f\" x=\"97.416016\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-67\" x=\"158.597656\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-72\" x=\"222.074219\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-61\" x=\"263.1875\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6d\" x=\"324.466797\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-20\" x=\"421.878906\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-52\" x=\"453.666016\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-75\" x=\"518.648438\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6e\" x=\"582.027344\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6e\" x=\"645.40625\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-69\" x=\"708.785156\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6e\" x=\"736.568359\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-67\" x=\"799.947266\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-20\" x=\"863.423828\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-54\" x=\"895.210938\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-69\" x=\"953.169922\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6d\" x=\"980.953125\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-65\" x=\"1078.365234\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-20\" x=\"1139.888672\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-43\" x=\"1171.675781\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6f\" x=\"1241.5\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6d\" x=\"1302.681641\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-70\" x=\"1400.09375\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-61\" x=\"1463.570312\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-72\" x=\"1524.849609\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-69\" x=\"1565.962891\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-73\" x=\"1593.746094\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6f\" x=\"1645.845703\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-6e\" x=\"1707.027344\"/>\n",
       "    </g>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"p660f5ca98f\">\n",
       "   <rect x=\"40.603125\" y=\"22.318125\" width=\"279\" height=\"221.76\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<Figure size 500x400 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 设置横坐标和对应的运行时间数据\n",
    "x = ['ori', 'no_subsampling', 'enhance_k']\n",
    "y = [7.55, 22.78, 13.23]\n",
    "\n",
    "d2l.set_figsize((5, 4))\n",
    "# 绘制柱状图\n",
    "bars = d2l.plt.bar(x, y)\n",
    "for rect in bars:\n",
    "    height = rect.get_height()\n",
    "    d2l.plt.text(rect.get_x() + rect.get_width() / 2, height,\n",
    "                 '%.2f' % height, ha='center', va='bottom')\n",
    "# 添加标题和标签\n",
    "d2l.plt.title('Program Running Time Comparison')\n",
    "d2l.plt.xlabel('Program')\n",
    "d2l.plt.ylabel('Running Time (s)')\n",
    "\n",
    "# 显示图形\n",
    "d2l.plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.3.3\n",
    "\n",
    "本节代码中的哪些其他超参数可能会影响数据加载速度？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;1.min_freq(Vocab里面)\n",
    "\n",
    "&emsp;&emsp;2.max_window_size\n",
    "\n",
    "&emsp;&emsp;3.num_works\n",
    "\n",
    "&emsp;&emsp;4.batch_size"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14.4 预训练word2vec"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.4.1\n",
    "\n",
    "使用训练好的模型，找出其他输入词在语义上相似的词。您能通过调优超参数来改进结果吗？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;可以通过调整超参数来改变词向量的质量。以下是一些常用的超参数：\n",
    "\n",
    "&emsp;&emsp;1.嵌入维度（embedding dimension）：这是词向量的长度。一般来说，维度越高，模型能够捕捉的语义信息就越多，但是会增加模型的复杂度和训练时间。因此，需要在维度和模型性能之间进行平衡。\n",
    "\n",
    "&emsp;&emsp;2.上下文窗口大小（context window size）：这是用来定义中心词周围的词语的范围。上下文窗口大小越大，模型能够捕捉到更多的上下文信息，但是也会增加噪声词的数量，使得训练时间增加。\n",
    "\n",
    "&emsp;&emsp;3.负采样数量（negative sampling count）：这是用来指定负样本的数量。增加负样本数量可以提高模型的鲁棒性，但是也会增加训练时间和计算复杂度。\n",
    "\n",
    "&emsp;&emsp;4.学习率（learning rate）：这是用来控制每次参数更新的步长。学习率越大，模型的收敛速度越快，但是也会增加训练过程中的不稳定性。\n",
    "\n",
    "&emsp;&emsp;通过调整这些超参数，可以改进词向量的质量，从而提高找到与输入词在语义上相似的词的准确性。一般来说，我们需要对不同的超参数组合进行实验，选择效果最好的一组超参数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.4.2\n",
    "\n",
    "当训练语料库很大时，在更新模型参数时，我们经常对当前小批量的*中心词*进行上下文词和噪声词的采样。换言之，同一中心词在不同的训练迭代轮数可以有不同的上下文词或噪声词。这种方法的好处是什么？尝试实现这种训练方法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;**好处:**\n",
    "\n",
    "&emsp;&emsp;1.提高训练速度：对于大型语料库，使用全量数据进行训练会导致计算量极大，而采用随机采样的方法可以使训练速度更快。\n",
    "\n",
    "&emsp;&emsp;2.提高模型泛化能力：使用随机采样可以使模型学习到更多的上下文和噪声，从而可以更好地泛化到未见过的数据中。\n",
    "\n",
    "&emsp;&emsp;3.减轻过拟合：使用随机采样可以减少模型对某些具体的上下文或噪声的过度拟合，从而提高模型的泛化能力。\n",
    "\n",
    "&emsp;&emsp;4.改善训练效果：随机采样可以使模型学习到更多的语言结构和规律，从而改善模型的训练效果。\n",
    "\n",
    "&emsp;&emsp;5.处理长尾词汇：随机采样可以使模型更好地学习到罕见词汇的语义信息，从而提高模型对于长尾词汇的处理能力。\n",
    "\n",
    "&emsp;&emsp;**实现:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14.5 全局向量的词嵌入（GloVe）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.5.1\n",
    "\n",
    "如果词$w_i$和$w_j$在同一上下文窗口中同时出现，我们如何使用它们在文本序列中的距离来重新设计计算条件概率$p_{ij}$的方法？提示：参见GloVe论文的第4.2节。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;在GloVe论文的第4.2节中，作者讨论了如何利用词wi和wj在同一个上下文窗口中出现的距离来重新设计计算条件概率pij的方法。具体地说，他们使用了一个称为“加权最小二乘”（Weighted Least Squares）的方法来优化模型。\n",
    "\n",
    "&emsp;&emsp;在这个方法中，作者定义了一个对数线性模型，该模型用来描述两个词在上下文中同时出现的频率与它们在整个语料库中共同出现的频率之间的关系。具体地说，作者使用以下形式的模型：\n",
    "$$\n",
    "log({X_{i\\,\\!j}}) = log({V_i}) + log({V_j}) + b\n",
    "$$\n",
    "&emsp;&emsp;其中，Xij表示wi和wj在上下文中同时出现的次数，Vi和Vj分别表示wi和wj在整个语料库中出现的总次数，而b是一个偏置项。\n",
    "\n",
    "&emsp;&emsp;为了使用词wi和wj在上下文中的距离来重新设计计算条件概率pij的方法，作者将模型修改为以下形式：\n",
    "$$\n",
    "f(d_{i\\,\\!j}) = log({X_{i\\,\\!j}}) - log({V_i}) - log({V_j})\n",
    "$$\n",
    "&emsp;&emsp;其中，dij表示wi和wj在文本序列中的距离，f是一个可调的函数。作者使用了一个函数f，使得f(dij)能够很好地近似于log(dij)。然后，他们使用加权最小二乘法来拟合这个新的模型，以找到最优的函数f和参数b。\n",
    "\n",
    "&emsp;&emsp;在拟合过程中，作者使用了一个权重函数h(dij)，用于调整每个样本的权重，使得距离更近的样本在拟合中具有更高的权重。最终，他们得到了一个重新设计的模型，可以用来计算两个词之间的条件概率pij，其中词wi和wj在上下文中的距离被考虑在内。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.5.2\n",
    "\n",
    "对于任何一个词，它的中心词偏置和上下文偏置在数学上是等价的吗？为什么？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;在 GloVe 中，中心词偏置和上下文偏置在数学上不是等价的，因为它们分别代表了不同的语言现象。\n",
    "\n",
    "&emsp;&emsp;中心词偏置是指一个词在所有上下文中出现的频率，而上下文偏置是指所有与一个词一起出现的单词的频率之和。这两个偏置量代表了不同的语言现象，因此在数学上它们是不等价的。\n",
    "\n",
    "&emsp;&emsp;例如，在一个文本中，词 \"the\" 可能在各种上下文中都经常出现，因此它的中心词偏置会很高。另一方面，如果一个文本中有很多与 \"dog\" 相关的单词（如 \"cat\"、\"pet\"、\"leash\" 等），那么 \"dog\" 的上下文偏置会很高。\n",
    "\n",
    "&emsp;&emsp;在 GloVe 模型中，中心词偏置和上下文偏置都被用来计算词之间的共现概率，但它们被赋予不同的权重。具体来说，中心词偏置被用来计算一个词在上下文中出现的频率，而上下文偏置被用来计算这个词与其他单词一起出现的频率。这种权重的分配可以让 GloVe 模型更好地捕捉不同词之间的语义关系，从而提高模型的性能。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14.6 子词嵌入"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.6.1\n",
    "\n",
    "例如，英语中大约有$3\\times 10^8$种可能的$6$-元组。子词太多会有什么问题呢？如何解决这个问题？提示:请参阅fastText论文第3.2节末尾。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;在英语中，一个 6 元组的子词数量大约有 3 x 10^8 个，这意味着如果我们使用 6-gram 子词，词汇表的大小将会大大增加，这会导致存储和计算成本的增加，并且会使得模型更加复杂，容易出现过拟合等问题。\n",
    "\n",
    "&emsp;&emsp;为了解决这个问题，fastText 使用了哈希技术来将子词映射到一个较小的固定大小的哈希表中，从而避免了子词数量的爆炸式增长。具体来说，fastText 将每个子词映射到一个唯一的哈希值，然后使用这些哈希值来表示子词，这样就可以将子词存储在一个固定大小的哈希表中。这种方法可以有效地减少模型的存储和计算成本，并且可以使得模型更加稳定和可靠。\n",
    "\n",
    "&emsp;&emsp;需要注意的是，使用哈希技术来处理子词可能会导致哈希冲突，即不同的子词可能被映射到相同的哈希值。为了解决这个问题，fastText 使用了一种称为“n-gram buckets”的技术，将具有相同哈希值的子词放置在同一个桶中，从而避免了哈希冲突的问题。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.6.2\n",
    "\n",
    "如何在连续词袋模型的基础上设计一个子词嵌入模型？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.6.3\n",
    "\n",
    "要获得大小为$m$的词表，当初始符号词表大小为$n$时，需要多少合并操作？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;在 fastText 中，用于构建词表的初始符号词表大小为 n，要获得大小为 m 的最终词表，最多需要进行`m-n`次合并操作。\n",
    "\n",
    "&emsp;&emsp;这是由于每次合并操作都会将两个子词合并为一个新的子词，在fastText中，词是由子词加和代表的，原来的词表为n，若在合并次数少于m-n的情况下，已经得到了能够表达m个词的所有子词，则会会提前终止合并，所以合并次数是会小于等于词表差值。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.6.4\n",
    "\n",
    "如何扩展字节对编码的思想来提取短语？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;1.对语料库中的所有单词应用字节对编码，将每个单词拆分为多个子词。\n",
    "\n",
    "&emsp;&emsp;2.遍历语料库中所有的单词，将相邻的子词组合成新的短语，并统计每个短语的出现次数。\n",
    "\n",
    "&emsp;&emsp;3.将出现次数最多的短语作为新的合并符号，并将其添加到词表中。然后，将语料库中所有的短语中包含该符号的部分替换为该符号，以生成新的语料库。\n",
    "\n",
    "&emsp;&emsp;4.重复步骤2和3，直到达到所需的短语数目或无法生成新的短语为止。\n",
    "\n",
    "&emsp;&emsp;5.通过这种方法，可以从语料库中提取出多个短语，这些短语可以用于构建更准确的文本表示。此外，这种方法还可以提高模型的泛化能力，因为模型可以更好地捕捉短语级别的语义信息。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14.7 词的相似度和类比任务"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.7.1\n",
    "\n",
    "使用`TokenEmbedding('wiki.en')`测试fastText结果。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;**将源代码改成下面的'wiki.en'即可：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "glove_6b50d = d2l.TokenEmbedding('wiki.en')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.7.2\n",
    "\n",
    "当词表非常大时，我们怎样才能更快地找到相似的词或完成一个词的类比呢？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;1.基于向量空间模型的方法：将每个单词表示为一个向量，通过计算向量之间的距离或相似度来寻找相似词或完成词类比。这种方法可以通过使用近似最近邻算法（如ANN）来加速计算。\n",
    "\n",
    "&emsp;&emsp;2.基于哈希表的方法：将每个单词映射到哈希表中的一个位置，然后通过比较哈希表中的位置来判断单词之间的相似性。这种方法可以通过使用一些高效的哈希函数和哈希表的优化技巧来提高速度。\n",
    "\n",
    "&emsp;&emsp;3.基于子词信息的方法：将单词分解为多个子词，并使用这些子词的向量来表示单词，从而可以更好地处理未登录词和词形变化。这种方法可以通过使用快速文本搜索算法（如Trie）来加速计算。\n",
    "\n",
    "&emsp;&emsp;4.基于近似算法的方法：使用一些近似算法来计算词向量之间的相似度，如局部敏感哈希（LSH）、随机投影和低秩近似等。这些算法可以大大减少计算时间和空间复杂度。\n",
    "\n",
    "&emsp;&emsp;总的来说，选择适合任务的算法和技术可以在大词表下提高相似词寻找和词类比的速度和准确度。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14.8 来自Transformer的双向编码器表示（BERT）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.8.1\n",
    "\n",
    "为什么BERT成功了？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;同期的模型ELMo对上下文进行双向编码，解决了一词多意等问题，但是智能使用特定于某个任务的架构，不能进行finetune；同期的GPT是任务无关性的，但是仅能从做导游对上下文进行编码。\n",
    "\n",
    "&emsp;&emsp;BERT结合了二者的优势，对上下文进行双向编码，且任务无关，对大多数nlp任务只需要对架构进行finetune即可。故BERT在同时期使用效果更好！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.8.2\n",
    "\n",
    "在所有其他条件相同的情况下，掩蔽语言模型比从左到右的语言模型需要更多或更少的预训练步骤来收敛吗？为什么？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;在其他条件相同的情况下，掩蔽语言模型需要更多的预训练步骤来收敛。这是因为掩蔽语言模型需要预测缺失的'mask'词汇，需要更高的上下文理解能力和更强的推理能力。而从左到右的语言模型只需要预测下一个词汇，相对而言更简单。\n",
    "  \n",
    "&emsp;&emsp;举个具体的例子：在BERT为提高上下文理解能力与推理能力所作的掩敝语言模型mlm中，选择15%的词元作为遮盖词元，且为了使后续不同下游任务能够微调，又进行了80%的时间将原始词元替换为mask；10%的时间设置为原所有文本中的随机词元；10%的时间保持原来的词元不变。上述操作增加了模型的复杂程度，所以迭代步数要更多。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.8.3\n",
    "\n",
    "在BERT的原始实现中，`BERTEncoder`中的位置前馈网络（通过`d2l.EncoderBlock`）和`MaskLM`中的全连接层都使用高斯误差线性单元（Gaussian error linear unit，GELU）作为激活函数。研究GELU与ReLU之间的差异。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;GELU是一种激活函数，与ReLU相比，它的主要差异在于它的形状更加平滑。ReLU在输入为负数时输出为0，而GELU在输入为负数时输出一个小的非零值，这使得GELU更加平滑。此外，GELU还具有一些其他的优势，例如在处理较大的数据集时具有更好的性能，以及对于一些复杂的神经网络模型，GELU能够提供更好的训练效果。总体来说，GELU是一种更加灵活和高效的激活函数，可以在许多不同的应用场景中发挥作用。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.9.1\n",
    "\n",
    "为简单起见，句号用作拆分句子的唯一分隔符。尝试其他的句子拆分技术，比如Spacy和NLTK。以NLTK为例，需要先安装NLTK：`pip install nltk`。在代码中先`import nltk`。然后下载Punkt语句词元分析器：`nltk.download('punkt')`。要拆分句子，比如`sentences = 'This is great ! Why not ?'`，调用`nltk.tokenize.sent_tokenize(sentences)`将返回两个句子字符串的列表：`['This is great !', 'Why not ?']`。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;先把shuffle去了好直观对比"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from d2l import torch as d2l\n",
    "import torch\n",
    "import os\n",
    "\n",
    "def _read_wiki2(data_dir):\n",
    "    file_name = os.path.join(data_dir, 'wiki.train.tokens')\n",
    "    with open(file_name, 'r', encoding='utf-8') as f:\n",
    "        lines = f.readlines()\n",
    "    # ⼤写字⺟转换为⼩写字⺟\n",
    "    paragraphs = [line.strip().lower().split(' . ')\n",
    "                    for line in lines if len(line.split(' . ')) >= 2]\n",
    "#     random.shuffle(paragraphs)\n",
    "    return paragraphs\n",
    "\n",
    "data_dir = d2l.download_extract('wikitext-2', 'wikitext-2')\n",
    "para_ori = _read_wiki2(data_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;可见原本是通过' . ' 来分割的，注意必须是dot两边都有一个空格才能分割"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5,\n",
       " ['it met with positive sales in japan , and was praised by both japanese and western critics',\n",
       "  'after release , it received downloadable content , along with an expanded edition in november of that year',\n",
       "  'it was also adapted into manga and an original video animation series',\n",
       "  \"due to low sales of valkyria chronicles ii , valkyria chronicles iii was not localized , but a fan translation compatible with the game 's expanded edition was released in 2014\",\n",
       "  'media.vision would return to the franchise with the development of valkyria : azure revolution for the playstation 4 .'])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(para_ori[2]), para_ori[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://mirrors.aliyun.com/pypi/simple/\n",
      "Collecting nltk\n",
      "  Downloading https://mirrors.aliyun.com/pypi/packages/a6/0a/0d20d2c0f16be91b9fa32a77b76c60f9baf6eba419e5ef5deca17af9c582/nltk-3.8.1-py3-none-any.whl (1.5 MB)\n",
      "     ---------------------------------------- 1.5/1.5 MB 744.3 kB/s eta 0:00:00\n",
      "Requirement already satisfied: click in e:\\anaconda\\envs\\pytorch\\lib\\site-packages (from nltk) (8.1.3)\n",
      "Requirement already satisfied: regex>=2021.8.3 in e:\\anaconda\\envs\\pytorch\\lib\\site-packages (from nltk) (2022.10.31)\n",
      "Requirement already satisfied: tqdm in e:\\anaconda\\envs\\pytorch\\lib\\site-packages (from nltk) (4.65.0)\n",
      "Requirement already satisfied: joblib in e:\\anaconda\\envs\\pytorch\\lib\\site-packages (from nltk) (1.2.0)\n",
      "Requirement already satisfied: colorama in e:\\anaconda\\envs\\pytorch\\lib\\site-packages (from click->nltk) (0.4.6)\n",
      "Installing collected packages: nltk\n",
      "Successfully installed nltk-3.8.1\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Ignoring invalid distribution -pencv-python (e:\\anaconda\\envs\\pytorch\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -pencv-python (e:\\anaconda\\envs\\pytorch\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -pencv-python (e:\\anaconda\\envs\\pytorch\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -pencv-python (e:\\anaconda\\envs\\pytorch\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -pencv-python (e:\\anaconda\\envs\\pytorch\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -pencv-python (e:\\anaconda\\envs\\pytorch\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -pencv-python (e:\\anaconda\\envs\\pytorch\\lib\\site-packages)\n"
     ]
    }
   ],
   "source": [
    "!pip install nltk"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;这个if判断条件是为了消去一些空字符行用的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[nltk_data] Downloading package punkt to\n",
      "[nltk_data]     C:\\Users\\xiao\\AppData\\Roaming\\nltk_data...\n",
      "[nltk_data]   Package punkt is already up-to-date!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(5,\n",
       " ['it met with positive sales in japan , and was praised by both japanese and western critics .',\n",
       "  'after release , it received downloadable content , along with an expanded edition in november of that year .',\n",
       "  'it was also adapted into manga and an original video animation series .',\n",
       "  \"due to low sales of valkyria chronicles ii , valkyria chronicles iii was not localized , but a fan translation compatible with the game 's expanded edition was released in 2014 .\",\n",
       "  'media.vision would return to the franchise with the development of valkyria : azure revolution for the playstation 4 .'])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import nltk\n",
    "nltk.download('punkt')\n",
    "\n",
    "def _read_wiki_nltk(data_dir):\n",
    "    file_name = os.path.join(data_dir, 'wiki.train.tokens')\n",
    "    with open(file_name, 'r', encoding='utf-8') as f:\n",
    "        lines = f.readlines()\n",
    "    # ⼤写字⺟转换为⼩写字⺟\n",
    "    paragraphs = [nltk.tokenize.sent_tokenize(line.strip().lower())\n",
    "                    for line in lines if len(line.split(' . ')) >= 2]\n",
    "#     random.shuffle(paragraphs)\n",
    "    return paragraphs\n",
    "\n",
    "para_nltk = _read_wiki_nltk(data_dir)\n",
    "len(para_nltk[2]), para_nltk[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# demo = nltk.tokenize.sent_tokenize(para_nltk[0])\n",
    "# len(demo), demo"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;可见nltk的作用体现了。区分二者可以人为再构造几个不同的标点符号："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(['This is great !', 'Why not ?', 'ah!a'], ['this is great ! why not ? ah!a'])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lined = 'This is great ! Why not ? ah!a'\n",
    "nltk.tokenize.sent_tokenize(lined), lined.strip().lower().split(' . ')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.9.2\n",
    "\n",
    "如果我们不过滤出一些不常见的词元，词量会有多大？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;将class _WikiTextDataset中的vocab中的min_freq=0即可，输出len(vocab)=28886"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14.10 预训练BERT"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.10.1\n",
    "\n",
    "在实验中，我们可以看到遮蔽语言模型损失明显高于下一句预测损失。为什么？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;掩蔽语言模型是一种预测中间掩盖掉的词的任务，相当于完形填空：它要求模型在给定上下文的一些词的情况下，预测中间扣除的词是什么。相比之下，下一句预测任务是要求模型在给定一句话的情况下，预测下一句话是什么。\n",
    "\n",
    "&emsp;&emsp;由此可知，掩蔽语言模型需要预测多个位置的单词，而下一句预测任务只需要预测一整句话，因此掩蔽语言模型需要更多的预测任务，模型需要更好地理解句子中的语言结构和上下文关系，才能准确地预测每个位置的单词，因此其损失会更大。\n",
    "\n",
    "&emsp;&emsp;**具体到本节中的例子而言:** 对下一句预测仅仅抽取了原句子中'cls'词元对应的hiddens信息，送入mlp的输入为(bs,1,h);而在mlm中，送入mlp的是(bs,Tmask,h),输出相应的hat值(bs,Tmask,len(vocab)),其中Tmask就是每个句子中需要预测的词元数量，书上表示的是10(模型更加复杂。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习14.10.2\n",
    "\n",
    "将BERT输入序列的最大长度设置为512（与原始BERT模型相同）。使用原始BERT模型的配置，如$\\text{BERT}_{\\text{LARGE}}$。运行此部分时是否遇到错误？为什么？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;笔者使用的4块2080ti，更改后会报OutOfMemoryError错误，是因为一次性读取的数据超出内存。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
